package com.tanqidi.arcgisandroid.data.project

import android.content.Context
import android.os.Environment
import com.google.gson.GsonBuilder
import com.tanqidi.arcgisandroid.App
import com.tanqidi.arcgisandroid.R
import com.tanqidi.arcgisandroid.base.utils.FileUtil
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flowOf
import java.io.File

class ProjectRepository(
    private val context: Context
) {
    val projectConfigFolder = Environment.getExternalStorageDirectory().absolutePath + File.separator + App.app!!.getString(R.string.app_name) + File.separator + App.app!!.getString(R.string.menu_project_config)
    val gson = GsonBuilder().setPrettyPrinting().create()

    /**
     * 保存一个配置文件
     */
    fun saveProject(project: Project) {
        val projectJson = gson.toJson(project)
        //创建project配置文件
        val projectConfigFile = File(projectConfigFolder, project.name+".json")
        //如果是覆盖的话，直接删除算了，然后重新写入
        projectConfigFile.delete()
        //将json写入
        FileUtil.write(projectConfigFile, projectJson)
    }

    /**
     * 根据文件名删除配置文件
     */
    fun deleteProjectByName(name: String){
        val file = File(projectConfigFolder + File.separator + name + ".json")
        if(file.exists()){
            file.delete()
        }
    }

    /**
     * 列表所有配置文件，转成对象
     */
    fun listProject(): List<Project> {
        val projectList = File(projectConfigFolder).listFiles()!!.map {
            val fileContent = FileUtil.readFile(it)
            val project = gson.fromJson(fileContent, Project::class.java)
            project
        }
        return projectList
    }

    // TODO: 测试代码，kotlin flow
    fun listProjectFlow() : Flow<List<Project>> {
        return flowOf(listProject())
    }

    /**
     * 根据项目名获取配置文件
     */
    fun getProjectByName(name: String): Project {
        val file = File(projectConfigFolder + File.separator + name + ".json")
        val fileContent = FileUtil.readFile(file)
        return gson.fromJson(fileContent, Project::class.java)
    }

    fun deleteProject(project: Project) {
        val file = File(projectConfigFolder + File.separator + project.name + ".json")
        file.delete()
    }

}